<template>
  <div class="chat-container">
    <h2>{{ characterName }} 的对话</h2>
    <div class="chat-box">
      <div
        v-for="(message, index) in chatMessages"
        :key="index"
        class="message"
      >
        <strong>{{ message.sender }}:</strong> {{ message.text }}
      </div>
    </div>
    <el-input
      v-model="userInput"
      placeholder="输入您的消息"
      @keyup.enter="sendMessage"
      class="chat-input"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const bookId = route.params.bookId

const characterName = ref('')
const userInput = ref('')
const chatMessages = ref([])

// 写死的角色数据
const characters = [
  { characterId: 1, name: '角色一' },
  { characterId: 2, name: '角色二' },
  { characterId: 3, name: '角色三' },
]

// 初始化角色名称
onMounted(() => {
  const character = characters.find((c) => c.characterId == characterId)
  if (character) {
    characterName.value = character.name
    chatMessages.value.push({
      sender: '系统',
      text: '开始与 ' + characterName.value + ' 的对话！',
    })
  }
})

// 发送消息
const sendMessage = () => {
  if (userInput.value.trim()) {
    chatMessages.value.push({ sender: '你', text: userInput.value })
    userInput.value = ''
    // 模拟角色回应
    setTimeout(() => {
      chatMessages.value.push({
        sender: characterName.value,
        text: `你好！我是${characterName.value}，很高兴和你聊天！`,
      })
    }, 1000)
  }
}
</script>

<style scoped>
.chat-container {
  padding: 20px;
}

.chat-box {
  border: 1px solid #ccc;
  padding: 10px;
  height: 300px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 10px;
}

.chat-input {
  width: 100%;
}
</style>
